import { ref } from 'vue'
import { API_URL } from '../config/apiConfig'
import { addAuthHeader } from './api/apiUtils'
import type { SensitiveWordsListItem } from '../types'
import { authStore } from './auth/store'
import { useRouter } from 'vue-router'

export function useSensitiveWordsManagement() {
  const sensitiveWordsList = ref<SensitiveWordsListItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  const fetchSensitiveWordsList = async () => {
    loading.value = true
    error.value = null
    const router = useRouter()
    
    try {
      const response = await fetch(`${API_URL}/demo/sensitive-words/list`, addAuthHeader(
        {
          credentials: 'include',
          method: 'GET'
        }
      ))
      
      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
          // 清除认证状态
          authStore.clearAuth()
          // 重定向到登录页面
          router.push('/')
          return
        }
        throw new Error(`请求失败: ${response.status}`)
      }
      
      const result = await response.json()
      sensitiveWordsList.value = result.data || []
    } catch (err) {
      console.error('获取敏感词列表失败:', err)
      error.value = '获取敏感词列表失败，请重试'
    } finally {
      loading.value = false
    }
  }

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    } catch (err) {
      return dateString
    }
  }

  const deleteSensitiveWord = async (id: string) => {
    try {
      const response = await fetch(`${API_URL}/demo/sensitive-words/delete?id=${id}`, addAuthHeader({
        method: 'DELETE'
      }))
      
      if (!response.ok) {
        throw new Error(`删除失败: ${response.status}`)
      }
      
      // 删除成功后刷新列表
      await fetchSensitiveWordsList()
      return true
    } catch (err) {
      console.error('删除敏感词失败:', err)
      return false
    }
  }

  const downloadSensitiveWord = async (id: string) => {
    window.open(`${API_URL}/demo/sensitive-words/${id}/download`, '_blank')
    // try {
    //   const response = await fetch(`${API_URL}/demo/sensitive-words/${id}/download`, addAuthHeader({
    //     method: 'GET'
    //   }))
    //
    //   if (!response.ok) {
    //     throw new Error(`下载失败: ${response.status}`)
    //   }
    //
    //   // 获取文件名
    //   const contentDisposition = response.headers.get('content-disposition')
    //   let filename = 'sensitive-words.txt'
    //
    //   if (contentDisposition) {
    //     const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
    //     if (filenameMatch && filenameMatch[1]) {
    //       filename = filenameMatch[1].replace(/['"]/g, '')
    //     }
    //   }
    //
    //   // 创建blob并下载
    //   const blob = await response.blob()
    //   const url = window.URL.createObjectURL(blob)
    //   const a = document.createElement('a')
    //   a.href = url
    //   a.download = filename
    //   document.body.appendChild(a)
    //   a.click()
    //   window.URL.revokeObjectURL(url)
    //   document.body.removeChild(a)
    //
    //   return true
    // } catch (err) {
    //   console.error('下载敏感词文件失败:', err)
    //   alert('下载敏感词文件失败，请重试')
    //   return false
    // }
  }

  return {
    sensitiveWordsList,
    loading,
    error,
    fetchSensitiveWordsList,
    formatDate,
    deleteSensitiveWord,
    downloadSensitiveWord
  }
}
